//
//  WHPayPasswordController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2019/1/14.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHPayPasswordController.h"
#import "WHInputInfoCell.h"
#import "WHCodeInfoCell.h"
#import "NSString+WH3DES.h"

@interface WHPayPasswordController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *dataTableView;
@property (nonatomic, strong) NSArray *tipsArray;
@property (nonatomic, strong) NSArray *placeHolderArray;
@property (nonatomic, strong) NSMutableArray *useInfoArray;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) NSURLSessionDataTask *codeTask;
@property (nonatomic, strong) NSURLSessionDataTask *setPayPasswordTask;

@end

@implementation WHPayPasswordController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"支付密码";
    [self initParams];
    [self setUpTableView];
}

- (void)initParams {
    _tipsArray = @[@"手机号码", @"验证码    ", @"支付密码", @"支付密码"];
    _placeHolderArray = @[@"", @"请输入验证码", @"请输入6位支付密码", @"请再次输入6位支付密码"];
    _useInfoArray = @[userManager.detailUserInfo.mobile, @"", @"", @""].mutableCopy;
}

- (void)setUpTableView {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:dataTableView];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    dataTableView.tableFooterView = [self tableFootView];
    
    [dataTableView registerClass:[WHInputInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHInputInfoCell class])];
    [dataTableView registerClass:[WHCodeInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHCodeInfoCell class])];
    dataTableView.backgroundColor = CViewBgMainColor;
    dataTableView.separatorColor = CLineColor;
    dataTableView.separatorInset = UIEdgeInsetsMake(0, KNormalSpace, 0, -KNormalSpace);
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top).offset(kTopHeight);
    }];
    _dataTableView = dataTableView;
}

- (UIView *)tableFootView {
    UIView *tableFootView = [[UIView alloc] init];
    tableFootView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(85));
    
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    submitButton.frame = CGRectMake(kRealwidth(32), kRealwidth(20), KScreenWidth-2*kRealwidth(32), kRealwidth(45));
    ViewRadius(submitButton, kRealwidth(45)/2);
    [tableFootView addSubview:submitButton];
    NSString *logoutTitle = @"确认";
    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:logoutTitle attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [submitButton setAttributedTitle:attributeStr forState:UIControlStateNormal];
    submitButton.backgroundColor = CMDarkOrangeColor;
    [submitButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    
    return tableFootView;
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource ——————

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _placeHolderArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1) {
        WHCodeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHCodeInfoCell class]) forIndexPath:indexPath];
        cell.tipsLabel.text = _tipsArray[indexPath.row];
        cell.messageField.text = _useInfoArray[indexPath.row];
        [cell setInputTextPlaceHolder:_placeHolderArray[indexPath.row]];
        [cell.rightTipsButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        
        kWeakSelf(self);
        cell.textChangeBlock = ^(NSString *text) {
            [weakself.useInfoArray replaceObjectAtIndex:indexPath.row withObject:text];
        };
        kWeakSelf(cell);
        cell.rightBtnClicked = ^{
            [weakself rightClickedAt:weakcell indexPath:indexPath];
        };
        
        return cell;
    } else {
        WHInputInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHInputInfoCell class]) forIndexPath:indexPath];
        cell.tipsLabel.text = _tipsArray[indexPath.row];
        cell.messageField.text = _useInfoArray[indexPath.row];
        [cell setInputTextPlaceHolder:_placeHolderArray[indexPath.row]];
        
        kWeakSelf(self);
        cell.textChangeBlock = ^(NSString *text) {
            [weakself.useInfoArray replaceObjectAtIndex:indexPath.row withObject:text];
        };
        if (indexPath.row == 0) {
            cell.validType = ValideTypePhoneNumber;
            cell.messageField.enabled = NO;
        } else if (indexPath.row == 2 || indexPath.row == 3) {
            cell.validType = ValideTypePayPassword;
            cell.messageField.enabled = YES;
        }
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(55);
}

#pragma mark - —————— 事件 ——————

- (void)rightClickedAt:(WHCodeInfoCell *)cell indexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];
    NSString *phoneNumber = _useInfoArray[0];
    
    if ([phoneNumber isEqualToString:@""]) {
        [WHView showMessage:@"请输入手机号" inView:self.view];
        return;
    }
    BOOL is = [WHValidationHelper validateMobile:phoneNumber];
    if (!is) {
        [WHView showMessage:@"请输入正确的手机号" inView:self.view];
        return;
    }
    
    _codeTask = [self getCodeWithPhoneNumber:phoneNumber completion:^(id responseObject) {
        if (ValidDict(responseObject)) {
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (errCode.intValue == 0) {
                [WHView showMessage:@"获取验证码成功" inView:self.view];
                [self startCountDown:cell];
            } else {
                [WHView showMessage:errorMsg inView:self.view];
            }
        }
    }];
    
}

- (void)startCountDown:(WHCodeInfoCell *)cell {
    __block int number = 60;
    cell.rightTipsButton.enabled = NO;
    __block NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0f block:^(NSTimer * _Nonnull timer) {
        DLog(@"%d", number);
        [cell.rightTipsButton setTitleColor:CFontContentGrayColor forState:UIControlStateNormal];
        [cell.rightTipsButton setTitle:[NSString stringWithFormat:@"重新发送(%d)", number] forState:UIControlStateNormal];
        number = number - 1;
        if (number == 0) {
            [cell.rightTipsButton setTitleColor:CMDarkOrangeColor forState:UIControlStateNormal];
            [cell.rightTipsButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            cell.rightTipsButton.enabled = YES;
            [timer invalidate];
            timer = nil;
        }
    } repeats:YES];
    _timer = timer;
}

- (void)submit:(UIButton *)button {
    [self.view endEditing:YES];
    NSString *phoneNumber = _useInfoArray[0];
    NSString *code = _useInfoArray[1];
    NSString *password = _useInfoArray[2];
    NSString *rePassword = _useInfoArray[3];
    
    if (phoneNumber.length == 0 || code.length == 0 || password.length == 0 || rePassword.length == 0) {
        [WHView showMessage:@"请完善以上信息" inView:self.view];
        return;
    }
    if (code.length != 6) {
        [WHView showMessage:@"请输入6位验证码" inView:self.view];
        return;
    }
    if (password.length != 6 || rePassword.length != 6) {
        [WHView showMessage:@"请输入6位支付密码" inView:self.view];
        return;
    }
    
    if (![password isEqualToString:rePassword]) {
        [WHView showMessage:@"两次输入密码不一致,请重新输入" inView:self.view];
        return;
    }
    
    kWeakSelf(self);
    [self setPayPasswordCompletion:^(id responseObject) {
        if (ValidDict(responseObject)) {
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];

            if (errCode.intValue == 0) {
                [WHView showHudMsgAtCenter:@"设置支付密码成功"];
                KPostNotification(KUserInfoChange, nil);
                [weakself.navigationController popViewControllerAnimated:YES];
            } else {
                [WHView showMessage:errorMsg inView:weakself.view];
            }
        }
    }];
}

#pragma mark - —————— 接口 ——————
/** 获取验证码 */
- (NSURLSessionDataTask *)getCodeWithPhoneNumber:(NSString *)phoneNumber completion:(completionBlock)completion {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_sendCode);
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          phoneNumber, @"userCell",
                          @"3", @"type",
                          @"1", @"systeam",
                          nil];
    return [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        completion(responseObject);
    } failure:^(NSError *error) {
        
    }];
}

- (void)setPayPasswordCompletion:(completionBlock)completion {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_insertPayPassWord);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          _useInfoArray[0], @"UserCell",
                          _useInfoArray[1], @"smsCode",
                          [NSString encryptUseDES3:_useInfoArray[2] key:DES3Key], @"payPassWord",
                          nil];
    
    _setPayPasswordTask = [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        completion(responseObject);
    } failure:^(NSError *error) {
        
    }];
}

- (void)backBtnClicked {
    if (_codeTask) {
        [_codeTask cancel];
        _codeTask = nil;
    }
    if (_setPayPasswordTask) {
        [_setPayPasswordTask cancel];
        _setPayPasswordTask = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)dealloc {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

@end
